
function resetSingleForm() {
    $('#single-guideline').val('none');
    $('#single-form').find('.guideline-control').slideUp();
    
    $('#single-type').val('dropdown');
    $('#single-data-source').val('custom');
    
    $('#single-form').find('.dropdown-control').show();
    $('#single-form').find('.radio-control').hide();
    $('#single-form').find('.custom-control').show();
    $('#single-form').find('.database-control').hide();
    
    $('#single-with-search').attr('checked', false);
    $('#single-with-image').attr('checked', false);
    $('#single-form').find('.image-control').hide();
    
    $('#single-label-text').val('');
    $('#single-name').val('');
    $('#single-id').val('');
    $('#single-placeholder').val('');
    $('#single-initial-value').val('');
}

function toSingleDropdown() {
    
    $('#single-modal-title').html('Dropdown Input');
    $('#single-save-btn').html('Create Dropdown Input');

    $('#single-label-text').attr('placeholder', 'Dropdown');
    $('#single-name').attr('placeholder', 'dropdown');
    $('#single-id').attr('placeholder', 'dropdown');
    $('#single-placeholder').attr('placeholder', 'Dropdown');
}

function toSingleRadio() {
    $('#single-modal-title').html('Radio Buttons');
    $('#single-save-btn').html('Create Radio Buttons');
    
    $('#single-type').val('radio');
    $('#single-data-source').val('custom');
    
    $('#single-form').find('.radio-control').slideDown();
    $('#single-form').find('.dropdown-control').slideUp();
    
    $('#single-label-text').attr('placeholder', 'Radio Button');
    $('#single-name').attr('placeholder', 'radio-button');
    $('#single-id').attr('placeholder', 'radio-button');
    $('#single-placeholder').attr('placeholder', 'Radio Button');
}

function createSingleData() {
    
    $('#single-custom-data-container div.data input.value').off();
    $('#single-custom-data-container div.data input.value').change(function(e) {
        e.preventDefault();
        var textEquiv = $(this).parent().find('input.text');
        textEquiv.val( $(this).val().toLowerCase().replace(/ /g,'_') );
    });
    
    $('#single-custom-data-container div.data a.btn-add').off();
    $('#single-custom-data-container div.data a.btn-add').click(function(e) {
        e.preventDefault();
        
        var dataOption = $(this).closest('div.data');
        var markup = '';
        
        var imagePath = $('#single-image-path').val();
        
         markup += '<div class="data">\n';
         markup += '<input type="text" name="single-data[][text]" class="form-control value input-sm" required="true" placeholder="Option Default Text">\n';
         markup += '<input type="text" name="single-data[][value]" class="form-control text input-sm" required="true" placeholder="Option Default Value">\n';
         markup += '<input type="text" name="single-data[][image]" class="form-control image input-sm image-control" required="true" placeholder="URL or path" value="' + imagePath + '">\n';
         markup += '<div class="btn-group btn-group-sm">\n';
         markup += '<a href="javascript:void(0)" class="btn btn-default btn-sm btn-add"><i class="fa fa-plus"></i></a>\n';
         markup += '<a href="javascript:void(0)" class="btn btn-default btn-sm btn-delete"><i class="fa fa-minus"></i></a>\n';
         markup += '</div>\n';
         markup += '</div>\n';
        
        dataOption.after(markup);
        
        $('#single-custom-data-container div.data a.btn-delete').click(function(e) {
            var toBeRemoved = $(this).closest('div.data');
            toBeRemoved.remove();
        });
        
        createSingleData();
        
        if( ! $('#single-with-image').prop('checked') ) {
            $('.image-control').hide();
        }
        
    });
}

$(function() {
    
    // validation rules
    var rules = {};
    rules['label']                          = set_rules('label', 'label', 'required|maxlength[6]');
    rules['label-text']                     = set_rules('label-text', 'label-text', 'required|maxlength[25]');
    rules['bold-label']                     = set_rules('bold-label', 'bold-label', 'maxlength[25]');
    rules['name']                           = set_rules('name', 'name', 'required|maxlength[50]');
    rules['id']                             = set_rules('id', 'id', 'required|maxlength[50]');
    rules['placeholder']                    = set_rules('placeholder', 'placeholder', 'maxlength[50]');
    rules['type']                           = set_rules('type', 'type', 'required|maxlength[25]');
    rules['image-path']                     = set_rules('image-path', 'image-path', 'required|maxlength[255]');
    
    rules['db-table-name']                  = set_rules('db-table-name', 'db-table-name', 'required|maxlength[255]');
    rules['singular-name']                  = set_rules('singular-name', 'singular-name', 'required|maxlength[255]');
    rules['plural-name']                    = set_rules('plural-name', 'plural-name', 'required|maxlength[255]');
    rules['foreign-key']                    = set_rules('foreign-key', 'foreign-key', 'required|maxlength[255]');
    rules['db-value']                       = set_rules('db-value', 'db-value', 'required|maxlength[255]');
    rules['db-text']                        = set_rules('db-text', 'db-text', 'required|maxlength[255]');
    rules['db-image']                       = set_rules('db-image', 'db-image', 'required|maxlength[255]');
    
    rules['show-list']                      = set_rules('show-list', 'show-list', 'maxlength[25]');
    rules['searchable']                     = set_rules('searchable', 'searchable', 'maxlength[25]');
    rules['show-api']                       = set_rules('show-api', 'show-api', 'maxlength[25]');
    rules['icon']                           = set_rules('icon', 'icon', 'required|maxlength[50]');
    rules['change-icon']                    = set_rules('change-icon', 'change-icon', 'maxlength[50]');
    rules['guideline']                      = set_rules('guideline', 'guideline', 'required|maxlength[50]');
    rules['guideline-title']                = set_rules('guideline-title', 'guideline-title', 'required|maxlength[50]');
    rules['guideline-text']                 = set_rules('guideline-text', 'guideline-text', 'required|maxlength[255]');
    rules['horizontal-size']                = set_rules('horizontal-size', 'horizontal-size', 'required|maxlength[25]');
    rules['position']                       = set_rules('position', 'position', 'required|maxlength[25]');

    // fieldset form validation
    $("#single-form").validate({
        errorElement: 'small',
        errorClass: 'help-block',
        rules: rules,
        errorPlacement:function(error, element) {
            element.parents('.input-size').append( '<div class="clear-fix"></div>' );
            element.parents('.input-size').append( error);
        },
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-error has-success').addClass('has-error');
        },
        success: function(label) {
            label.addClass('valid').closest('.form-group').removeClass('has-error has-success').addClass('has-success');
        }
    });
    
    resetSingleForm();
    createSingleData();
    
    // show/hide label controls
    $('#single-label').change(function() {
        if( $(this).val() === 'none' ) {
            $('#single-form').find('.label-control').slideUp();
        } else {
            $('#single-form').find('.label-control').slideDown();
        }
    });
    
    // auto fill-up single name and id using label text
    $('#single-label-text').change(function() {
        var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
        ( $('#single-name').val() === '' || $('#single-name').val() === undefined ) ? $('#single-name').val(textLabel) : '';
        ( $('#single-id').val() === '' || $('#single-id').val() === undefined ) ? $('#single-id').val(textLabel) : '';
        ( $('#single-placeholder').val() === '' || $('#single-placeholder').val() === undefined ) ? $('#single-placeholder').val($(this).val()) : '';
    });
    
    // auto fill-up single id using name
    $('#single-name').change(function() {
        if( $('#single-label').val() === 'none' ) {
            var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
            ( $('#single-id').val() === '' || $('#single-id').val() === undefined ) ? $('#single-id').val(textLabel) : '';
            ( $('#single-placeholder').val() === '' || $('#single-placeholder').val() === undefined ) ? $('#single-placeholder').val($(this).val()) : '';
        }
    });
    
    // show/hide icon controls
    $('#single-icon').change(function() {
        if( $(this).val() === 'none' ) {
            $('#single-form').find('.icon-control').slideUp();
        } else {
            $('#single-form').find('.icon-control').slideDown();
        }
    });
    
    // show/hide guideline controls
    $('#single-guideline').change(function() {
        if( $(this).val() === 'none' ) {
            $('#single-form').find('.guideline-control').slideUp();
        } else if(  $(this).val() === 'label' ) {
            $('#single-form').find('.guideline-control').slideDown();
            $('#single-guideline-title-container').slideUp();
        } else {
            $('#single-form').find('.guideline-control').slideDown();
        }
    });
    
    // clear all data fields
    $('#single-clear-btn').click(function() {
        $('#single-custom-data-container div.data').not('#single-custom-data-container div.data:first-child').remove();
    });
    
    // single type
    $('#single-type').change(function() {
        if( $(this).val() === 'radio' ) {
            resetSingleForm();
            toSingleRadio();
        }
        if( $(this).val() === 'dropdown' ) {
            resetSingleForm();
            toSingleDropdown();
            $('#single-form').find('.dropdown-control').slideDown();
        }
    });
    
    // single data
    $('#single-data-source').change(function() {
        if( $(this).val() === 'database' ) {
            $('#single-form').find('.database-control').slideDown();
            $('#single-form').find('.custom-control').slideUp();
            if( ! $('#single-with-image').is(':checked')  ) {
                $('#single-db-image-container').hide();
            }
        }
        if( $(this).val() === 'custom' ) {
            $('#single-form').find('.custom-control').slideDown();
            $('#single-form').find('.database-control').slideUp();
        }
    });
    
    // single with image
    $('#single-with-image').change(function() {
        if($(this).prop('checked') === true) {
            $('#single-form').find('.image-control').slideDown();
            if( $('#single-data-source').val() === 'custom') {
                $('#single-db-table-image-container').hide();
            }
        } else {
            $('#single-form').find('.image-control').slideUp();
        }
    });
    
    $('#single-save-btn').click(function(event) {
        event.preventDefault();
        $('#single-form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#single-form').valid()) {
            
            var values                  = $('#single-form').serializeJSON();
            
            // label
            var label                   = ( values['label'] !== undefined && values['label'] !== '' ) ? values['label'] : '';
            var labelPosition           = ( label !== '' || label !== 'none' ) ? ' align-' + label : 'none';
            var labelText               = ( values['label-text'] !== undefined && values['label-text'] !== '' ) ? values['label-text'] : '';
            
            // field data
            var fieldName               = ( values['name'] !== undefined && values['name'] !== '' ) ? values['name'] : '';
            var fieldId                 = ( values['id'] !== undefined && values['id'] !== '' ) ? values['id'] : '';
            var placeholder             = ( values['placeholder'] !== undefined && values['placeholder'] !== '' ) ? ' placeholder="' +values['placeholder']+ '"' : '';
            var type                    = ( values['type'] !== undefined && values['type'] !== '' ) ? values['type'] : '';
            
            var dataSource              = ( values['data-source'] !== undefined && values['data-source'] !== '' ) ? values['data-source'] : '';           
            var withSearch              = ( values['with-search'] !== undefined && values['with-search'] !== '' ) ? true : false;           
            var withImage               = ( values['with-image'] !== undefined && values['with-image'] !== '' ) ? true : false;           
            var singleData              = ( values['single-data'] !== undefined && values['single-data'] !== '' ) ? values['single-data'] : ''; 
            var radioInline             = ( values['radio-inline'] !== undefined && values['radio-inline'] !== '' ) ? ' radio-inline' : '';
            
            // database
            var databaseName            = ( values['db-table-name'] !== undefined && values['db-table-name'] !== '' ) ? values['db-table-name'] : 'none';           
            var databaseAttributeValue  = ( values['db-value'] !== undefined && values['db-value'] !== '' ) ? values['db-value'] : 'none';           
            var databaseAttributeText   = ( values['db-text'] !== undefined && values['db-text'] !== '' ) ? values['db-text'] : 'none';           
            var databaseAttributeImage  = ( values['db-image'] !== undefined && values['db-image'] !== '' ) ? values['db-image'] : 'none';           

            // guideline
            var guideline               = ( values['guideline'] !== undefined && values['guideline'] !== '' ) ? values['guideline'] : '';
            var guidelineTitle          = ( values['guideline-title'] !== undefined && values['guideline-title'] !== '' ) ? values['guideline-title'] : '';
            var guidelineText           = ( values['guideline-text'] !== undefined && values['guideline-text'] !== '' ) ? values['guideline-text'] : '';
            
            // size and position
            var horizontalSize          = ( values['horizontal-size'] !== undefined && values['horizontal-size'] !== '' ) ? ' ' + values['horizontal-size'] : '';
            var verticalSize            = ( values['vertical-size'] !== undefined && values['vertical-size'] !== '' )? ' ' + values['vertical-size'] : '';
            var position                = ( values['position'] !== undefined && values['position'] !== '' ) ? ' ' + values['position'] : '';
            
            // validations
            var validations             = values['validations'];
            var required                = $.inArray('required', validations) !== -1 ? ' required="true" ' : ' ';
            var requiredLabel           = ( $.inArray('required', validations) !== -1 && values['label'] !== '' && values['label'] !== 'none') ? ' *' : '';
            
            // icon
            var hasIcon                 = ( values['icon'] !== undefined &&  values['icon'] !== '' && values['icon'] !== 'none' ) ? true : false;
            var icon                    = ( values['icon'] !== undefined && values['icon'] !== '' ) ? values['icon'] : 'none';
            var changeIcon              = ( values['change-icon'] !== undefined && values['change-icon'] !== '' ) ? values['change-icon'] : '<i class="fa fa-list"></i>';

            var markup = '';
            var list = $('<li class="form-group row"></li>');
            markup += '<button type="button" class="close" aria-hidden="true">&times;</button>\n';
            markup += '<label for="' +fieldId+ '" class="control-label' +labelPosition+ ' col-3">\n';
            markup += labelText + requiredLabel + '\n';
            markup += '<br><small>' +guidelineText+ '</small>\n';
            markup += '</label>\n';
            markup += '<div class="control-group col-9">\n';
            markup += '<div class="input-size' + horizontalSize + position + '">\n';
            
            
            if( type === 'dropdown' ) {
                if( hasIcon ) {
                    markup += '<div class="input-group">';
                }
                if( hasIcon && ( icon === 'left' || icon === 'both' ) ) {
                    markup += '<span class="input-group-addon">' +changeIcon+ '</span>';
                }
                
                markup += '<select name="' + fieldName + '" id="' + fieldId + '" class="form-control' + verticalSize + '"' + placeholder +  required + '">';
                
                if( dataSource === 'custom' ) {
                    $.each( singleData, function(idx, obj) {
                        
                        var value = ( singleData[idx]['value'] !== undefined) ? ' value="' + singleData[idx]['value'] + '"' : '';
                        var text = ( singleData[idx]['text'] !== undefined) ? singleData[idx]['text'] : '';
                        var dataImage = ( singleData[idx]['image'] !== undefined) ? singleData[idx]['image'] : '';
                        
                        if( withImage ) {
                            if( dataImage.indexOf('http') !== -1 || dataImage.indexOf('www') !== -1 ) {
                                dataImage = ' data-img-src="' + dataImage + '"';
                            } else {
                                dataImage = ' data-img-src="' + base_url + dataImage + '"';
                            }
                        } else {
                            dataImage = '';
                        }

                        markup += '<option' + dataImage + value + '>' +text+ '</option>';
                        
                    });
                }
                
                if( dataSource === 'database' ) {
                        
                    var singleData = {};
                    singleData['db-name']          = databaseName;
                    singleData['db-attr-value']    = databaseAttributeValue;
                    singleData['db-attr-text']     = databaseAttributeText;
                    singleData['db-attr-image']    = databaseAttributeImage;
                    
                    var dbData = doPost( base_url + 'generator/data', singleData, 'json');
                    
                    $.each( dbData, function(idx, obj) {
                        
                        var value = (dbData[idx]['value'] !== undefined) ? ' value="' + dbData[idx]['value'] + '"' : '';
                        var text = (dbData[idx]['text'] !== undefined) ? dbData[idx]['text'] : '';
                        var dataImage = (dbData[idx]['image'] !== undefined) ? dbData[idx]['image'] : '';
                        
                        if( withImage ) {
                            dataImage = ' data-img-src="' + base_url + $('#single_image_path').val() + dataImage + '"';
                        } else {
                            dataImage = '';
                        }
                        markup += '<option' + value + dataImage + '>' +text+ '</option>';
                    });
                }
                markup += '</select>\n';
                if( hasIcon && ( icon === 'right' || icon === 'both' ) ) {
                    markup += '<span class="input-group-addon">' +changeIcon+ '</span>';
                }
                if( hasIcon ) {
                    markup += '</div>';
                }
            }
            
            if( type === 'radio' ) {

                if( dataSource === 'custom' ) {
                    $.each( singleData, function(idx, obj) {
                        var checked = idx === 0 ? ' checked="checked"' : '';
                        markup += '<div class="radio' + radioInline + '">\n';
                        markup += '<label class="control-label"><input type="radio" name="' + fieldName + '" value="' + singleData[idx]['value'] + '"' + checked + '>' + singleData[idx]['text'] + '</label>\n';
                        markup += '</div>\n';
                    });
                }
                
                if( dataSource === 'database' ) {
                        
                    var singleData = {};
                    singleData['db-name']          = databaseName;
                    singleData['db-attr-value']    = databaseAttributeValue;
                    singleData['db-attr-text']     = databaseAttributeText;
                    singleData['db-attr-image']    = databaseAttributeImage;
                    
                    var dbData = doPost( base_url + 'generator/data', singleData, 'json');
                    
                    $.each( dbData, function(idx, obj) {
                        
                        var checked = idx === 0 ? ' checked="checked"' : '';
                        var value   = (dbData[idx]['value'] !== undefined) ? ' value="' + dbData[idx]['value'] + '"' : '';
                        var text    = (dbData[idx]['text'] !== undefined) ? dbData[idx]['text'] : '';
                        
                        markup += '<div class="radio' + radioInline + '">\n';
                        markup += '<label class="control-label"><input type="radio" name="' + fieldName + '"' + value + checked + '>' + text + '</label>\n';
                        markup += '</div>\n';

                    });
                }
            }

            markup += '</div>\n';
            markup += '</div>\n';
            
            list.html(markup);
            list.data('controls', values);
            
            $('#form-sortable li:first-child fieldset:first-child ul').prepend(list);
            
            if( withSearch || withImage) {
                $('#' + fieldId).chosen({});
            }
            
            $('#single-modal').modal('hide');

        }
        
        // submit form for validation purposes
        $('#single-form').submit();

    });
    
    // generic single button
    $('#generic-single-btn').click(function() {
        resetSingleForm();
        $('#single-type-container').show();
        $('#single-modal').modal({
            width: '95%'
        });
    });
    
    // radio button
    $('#radio-btn').click(function() {
        resetSingleForm();
        toSingleRadio();
        $('#single-type-container').hide();
        $('#single-modal').modal({
            width: '95%'
        });
    });
    
    // dropdown menu
    $('#single-dropdown-btn').click(function() {
        resetSingleForm();
        toSingleDropdown();
        $('#single-type-container').hide();
        $('#single-modal').modal({
            width: '95%'
        });
    });
    
});

/*
 * General Function for AJAX Calls
 * @param string url URL for ajax call
 * @param string data Serialize data to be passed
 * @param string format Format of the resoponse text,json or xml
 * @returns object
 */
function doPost(url, data, format)
{
    var data;
    $.ajax({
        type: 'POST',
        url: url,
        dataType: format,
        data: data,
        async: false,
        success: function(res) {
            data = res;
        }
    });
    return data;
}